package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chivorn.datetimeoptionspicker.DateTimePickerView;
import com.chivorn.datetimeoptionspicker.OptionsPickerView;
import com.chivorn.datetimeoptionspicker.model.IPickerViewData;
import com.chivorn.datetimeoptionspicker.view.WheelOptions;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.CheckWorkViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityCheckWorkBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.AppMonthlyModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.ui.Wait;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 每月考勤
 */
public class CheckWorkActivity extends BaseActivity implements CheckWorkViewAdapter.CheckWorkListItemClickListener, View.OnClickListener, DateTimePickerView.OnTimeSelectListener {
    private ActivityCheckWorkBinding binding;
    private Context mContext;
    private CheckWorkViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private static final int TYPE_ACTION = 0x009;
    private Calendar calendar = null;//Calendar.getInstance();
    private String areaId;
    private String areaName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_check_work);
        setActionBar(true, "考核列表");
        mContext = this;

        areaId = AppModel.getNingBoAreaID(mContext);

        listViewAdapter = new CheckWorkViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.dateYm.setOnClickListener(this);
        binding.address.setOnClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        JSONObject param = new JSONObject();
        param.put("year", calendar == null ? "0" : calendar.get(Calendar.YEAR));
        param.put("month", calendar == null ? "0" : calendar.get(Calendar.MONTH) + 1);
        param.put("areaid", areaId);
        param.put("pageIndex", pageNo);
        param.put("pageRows", pageSize);
        param.put("assessmentDateStart", "");
        param.put("assessmentDateEnd", "");
        AppMonthlyModel.GetMonthlyAssessmentQuery(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("TotalCount");
                JSONArray array = data.getJSONArray("Rows");
                binding.ptrClassicFrameLayout.setLoadMoreEnable(!(count < pageSize));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.refreshComplete();
                showMsg(error);
            }
        });
    }

    private void queryMore() {
        pageNo += 1;
        JSONObject param = new JSONObject();
        param.put("year", calendar == null ? "0" : calendar.get(Calendar.YEAR));
        param.put("month", calendar == null ? "0" : calendar.get(Calendar.MONTH) + 1);
        param.put("areaid", areaId);
        param.put("pageIndex", pageNo);
        param.put("pageRows", pageSize);
        param.put("assessmentDateStart", "");
        param.put("assessmentDateEnd", "");
        AppMonthlyModel.GetMonthlyAssessmentQuery(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject data = JSON.parseObject(val);
                long count = data.getLong("TotalCount");
                JSONArray array = data.getJSONArray("Rows");
                binding.ptrClassicFrameLayout.loadMoreComplete(!(count < (pageNo * pageSize)));
                listViewAdapter.addItems(array);
            }

            @Override
            public void error(String error, String action) {
                binding.ptrClassicFrameLayout.loadMoreComplete(false);
                showMsg(error);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add_list_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (!NetWorkUtils.isNetworkConnected(this)) {
            showMsg(getString(R.string.no_network));
            return false;
        }
        switch (item.getItemId()) {
            case R.id.action_add:
                if (calendar == null) {
                    Toast.makeText(mContext, "请选择年月", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (StringUtil.isNull(areaId)) {
                    Toast.makeText(mContext, "请选择乡镇街道", Toast.LENGTH_SHORT).show();
                    break;
                }

                Bundle bundle = new Bundle();
                bundle.putString("areaId", areaId);
                bundle.putString("year", StringUtil.getValue(calendar.get(Calendar.YEAR)));
                bundle.putString("month", StringUtil.getValue(calendar.get(Calendar.MONTH) + 1));
                bundle.putString("areaName", areaName);
                toActivityForResult(CheckWorkDetailActivity.class, bundle, TYPE_ACTION);
                break;
            case R.id.btn_001:
                calendar = null;
                binding.dateYm.setText("");
                binding.address.setText("");
                areaId = AppModel.getNingBoAreaID(mContext);
                binding.ptrClassicFrameLayout.autoRefresh();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }

        try {
            JSONObject item = (JSONObject) listViewAdapter.getItem(position);
            Bundle bundle = new Bundle();
            bundle.putString(DefaultModel.PAGE_DATA_ID, StringUtil.dTs(item.getString("ID")));
            bundle.putString("areaName", item.getString("AREANAME"));
            String yearMonth = item.getString("YEAR_MONTH");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月", Locale.CHINA);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateFormat.parse(yearMonth));
            bundle.putString("year", StringUtil.getValue(calendar.get(Calendar.YEAR)));
            bundle.putString("month", StringUtil.getValue(calendar.get(Calendar.MONTH) + 1));
            toActivityForResult(CheckWorkDetailActivity.class, bundle, TYPE_ACTION);
        } catch (Exception e) {

        }
    }

    private ImageView getImageView(LinearLayout view) {
        return (ImageView) view.getChildAt(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == TYPE_ACTION) {
            binding.ptrClassicFrameLayout.autoRefresh();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.date_ym: {
                if (calendar == null)
                    calendar = Calendar.getInstance();
                DateTimePickerView pickerView = new DateTimePickerView.Builder(mContext, this)
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .setCancelText("取消")
                        .setSubmitText("确认")
                        .setOutSideCancelable(false)
                        .setLabel("年", "月", "日", "时", "分", "秒")
                        .setDate(calendar)

                        .build();
                pickerView.show();
                break;
            }
            case R.id.address: {
                changeArea();
                break;
            }
        }
    }

    @Override
    public void onTimeSelect(Date date, View v) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月", Locale.CHINA);
        calendar.setTime(date);
        binding.dateYm.setText(dateFormat.format(calendar.getTime()));
        binding.ptrClassicFrameLayout.autoRefresh();
    }

    //===============县市区、乡镇联动============
    List<PickerData> optionItems0 = new ArrayList<>();
    List<List<PickerData>> optionItems1 = new ArrayList<>();

    private void changeArea() {
        final OptionsPickerView pickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                JSONObject arg0 = optionItems0.get(options1).getData();
                JSONObject arg1 = optionItems1.get(options1).get(option2).getData();
                StringBuilder sb = new StringBuilder();
                areaId = StringUtil.dTs(arg0.getString("ID"));
                areaName = arg0.getString("NAME");
                sb.append(areaName);
                if (!"-1".equals(StringUtil.dTs(arg1.getString("ID")))) {
                    areaId = StringUtil.dTs(arg1.getString("ID"));
                    areaName = arg1.getString("NAME");
                    sb.append("/").append(areaName);
                }
                binding.address.setText(sb.toString());
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }).setCancelText("取消")
                .setSubmitText("确认").build();
        pickerView.setOnOptionChangeListener(new WheelOptions.OnOptionChangeListener() {
            @Override
            public void onChange(final int a, final int b, final int c) {
                if (b != -1)
                    return;
                String areaId = optionItems0.get(a).getData().getString("ID");
                if (StringUtil.isNull(areaId)) {
                    return;
                }

                setOptionItems1(pickerView, areaId, a);
            }
        });

        if (!optionItems0.isEmpty()) {
            pickerView.setPicker(optionItems0, optionItems1);
            int a = 0, b = 0;
            for (int i = 0, j = optionItems0.size(); i < j; i++) {
                PickerData data = optionItems0.get(i);
                if (StringUtil.dTs(data.getData().getString("ID")).equals(areaId)) {
                    a = i;
                    break;
                }
            }
            for (int i = 0, j = optionItems1.size(); i < j; i++) {
                List<PickerData> datas = optionItems1.get(i);
                boolean stop = false;
                for (int k = 0, m = datas.size(); k < m; k++) {
                    PickerData data = datas.get(k);
                    if (StringUtil.dTs(data.getData().getString("ID")).equals(areaId)) {
                        a = i;
                        b = k;
                        stop = true;
                        break;
                    }
                }
                if(stop)
                    break;
            }
            pickerView.setSelectOptions(a, b);
            pickerView.show();

            return;
        }

        setOptionItems0(pickerView);
    }

    private void setOptionItems0(final OptionsPickerView pickerView) {
        Wait.sharedInstance().start(mContext);
        JSONObject param = new JSONObject();
        param.put("areaid", AppModel.getNingBoAreaID(mContext));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                Wait.sharedInstance().stop();
                JSONArray items = JSON.parseArray(val);
                for (int i = 0, j = items.size(); i < j; i++) {
                    optionItems0.add(new PickerData(items.getJSONObject(i)));
                    List<PickerData> child = new ArrayList<>();
                    JSONObject d = new JSONObject();
                    d.put("ID", "");
                    d.put("NAME", "加载中...");
                    child.add(new PickerData(d));
                    optionItems1.add(child);
                }
                pickerView.setPicker(optionItems0, optionItems1);
                pickerView.show();
                final String areaId = StringUtil.dTs(items.getJSONObject(0).getString("ID"));
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setOptionItems1(pickerView, areaId, 0);
                    }
                }, 50);
            }

            @Override
            public void error(String error, String action) {
                Wait.sharedInstance().stop();
            }
        });
    }

    private void setOptionItems1(final OptionsPickerView pickerView, String areaId, final int a) {
        JSONObject param = new JSONObject();
        param.put("areaid", StringUtil.dTs(areaId));
        param.put("areaidByIdentity", AppLoginModel.getAreaId(mContext));
        AppContactsModel.GetNextLevelAreaID(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                List<PickerData> array = optionItems1.get(a);
                JSONObject c = array.get(0).getData();
                c.put("ID", "-1");
                c.put("NAME", "-请选择-");
                JSONArray items = JSON.parseArray(val);
                for (int i = 0, j = items.size(); i < j; i++) {
                    array.add(new PickerData(items.getJSONObject(i)));
                }
                pickerView.setSelectOptions(a, 0);
            }

            @Override
            public void error(String error, String action) {

            }
        });
    }

    private class PickerData implements IPickerViewData {
        private JSONObject data;

        public PickerData(JSONObject data) {
            this.data = data;
        }

        public JSONObject getData() {
            return data;
        }

        public void setData(JSONObject data) {
            this.data = data;
        }

        @Override
        public String getPickerViewText() {
            return data.getString("NAME");
        }
    }
}
